package com.coolw.data.migrate.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.function.Consumer;

/**
 * 编程式事务工具类
 * 使用:transactionUtils.transactional(t -> method(list));
 *
 * @author coolw
 * @version 1.0
 * @date 2024/5/30 10:20
 */
@Slf4j
@Component
public class TransactionUtil {

    private static PlatformTransactionManager transactionManager;

    @Autowired
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        TransactionUtil.transactionManager = transactionManager;
    }

    public static <T> boolean transactional(Consumer<T> consumer) {
        return transactional(consumer, true);
    }

    public static <T> boolean transactional(Consumer<T> consumer, boolean rollback) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            consumer.accept(null);
            transactionManager.commit(status);
            return true;
        } catch (Exception e) {
            log.warn("编程式事务处理异常", e);
            if (rollback) {
                transactionManager.rollback(status);
            }
            return false;
        }
    }
}
